package web.homework;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.*;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {//1111
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String contactInfo = request.getParameter("contactInfo");
        String address = request.getParameter("address");
        String email = request.getParameter("email");
        String password = request.getParameter("password"); // 密码应在服务器端加密

        if (name == null || contactInfo == null || address == null || email == null || password == null) {
            response.getWriter().write("Error: Missing parameters");
            return;//1111
        }

        try {
            Connection conn = DatabaseUtil.getConnection();
            String sql = "INSERT INTO Users (Name, ContactInfo, Address, Email, PasswordHash, RegistrationDate) VALUES (?, ?, ?, ?, ?, NOW())";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, name);
            pstmt.setString(2, contactInfo);
            pstmt.setString(3, address);
            pstmt.setString(4, email);
            pstmt.setString(5, password); // 在实际应用中应该加密密码
            int affectedRows = pstmt.executeUpdate();

            if (affectedRows > 0) {
                response.getWriter().write("User registered successfully");
            } else {
                response.getWriter().write("Error: User not registered");
            }

            DatabaseUtil.close(conn, pstmt, null);
        } catch (SQLException e) {
            e.printStackTrace();
            response.getWriter().write("Database error: " + e.getMessage());
        }
    }
}